//s20是代表20秒 h是指小时，如12小时则是：h12 d是天数，30天则：d30
//写cookies setCookie("name","hayden",'s20');
function setCookie(name, value, time) {
    let strsec;
    if (time == undefined) {
        var Days = 30; //默认30天有效期
        strsec = Days * 24 * 60 * 60 * 1000;
    } else {
        strsec = getsec(time) * 1;
    }
    var exp = new Date();
    exp.setTime(exp.getTime() + strsec);
    document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + ";path=/";
}


// 读取cookies getCookie("name")
function getCookie(name) {
    let arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg)) {
        return unescape(arr[2]);
    } else {
        return null;
    }

}


// 删除cookies delCookie('name')
function delCookie(name) {
    let exp = new Date();
    exp.setTime(exp.getTime() - 1);
    let cval = getCookie(name);
    if (cval != null)
        document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString() + ";path=/";
}


// 设置cookie时间
function getsec(str) {
    let str1 = str.substring(1, str.length) * 1;
    let str2 = str.substring(0, 1);
    if (str2 == "s") {
        return str1 * 1000;
    } else if (str2 == "h") {
        return str1 * 60 * 60 * 1000;
    } else if (str2 == "d") {
        return str1 * 24 * 60 * 60 * 1000;
    }
}

/* 验证码倒计时 */
function CutTime(time, fn1, fn2) {
    let _AllTime = time * 1;
    let _T = null;
    clearInterval(_T);
    _T = setInterval(function () {
        if (time <= 0) {
            clearInterval(_T);
            if (fn1) fn1(_AllTime);
        } else {
            time--;
            if (fn2) fn2(time);
        }
    }, 1000)
}


/**
  * 串联加载指定的脚本
  * 串联加载[异步]逐个加载，每个加载完成后加载下一个
  * 全部加载完成后执行回调
  * @param array|string 指定的脚本们
  * @param function 成功后回调的函数
  * @return array 所有生成的脚本元素对象数组
 var scripts = [
 "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js",
 "http://wellstyled.com/files/jquery.debug/jquery.debug.js"
 ];

 //这两个文件分别是 jQuery 1.4.的库文件和 jQuery Debug 插件
 //然后你可以使用下面的方法调用并在成功后执行回调了。

 seriesLoadScripts(scripts,function(){   alert('脚本加载完成啦'); });
 parallelLoadScripts(scripts,function(){   alert('脚本加载完成啦'); });

  */

function seriesLoadScripts(scripts, callback) {
    if (typeof (scripts) != "object") var scripts = [scripts];
    var HEAD = document.getElementsByTagName("head").item(0) || document.documentElement;
    var s = new Array(),
        last = scripts.length - 1,
        recursiveLoad = function (i) { //递归
            s[i] = document.createElement("script");
            s[i].setAttribute("type", "text/javascript");
            s[i].onload = s[i].onreadystatechange = function () { //Attach handlers for all browsers
                if (!0 || this.readyState == "loaded" || this.readyState == "complete") {
                    this.onload = this.onreadystatechange = null;
                    this.parentNode.removeChild(this);
                    if (i != last) recursiveLoad(i + 1); else if (typeof (callback) == "function") callback();
                }
            }
            s[i].setAttribute("src", scripts[i]);
            HEAD.appendChild(s[i]);
        };
    recursiveLoad(0);
}


/**
  * 并联加载指定的脚本
  * 并联加载[同步]同时加载，不管上个是否加载完成，直接加载全部
  * 全部加载完成后执行回调
  * @param array|string 指定的脚本们
  * @param function 成功后回调的函数
  * @return array 所有生成的脚本元素对象数组
  */

function parallelLoadScripts(scripts, callback) {
    if (typeof (scripts) != "object") var scripts = [scripts];
    var HEAD = document.getElementsByTagName("head").item(0) || document.documentElement,
        s = new Array(),
        loaded = 0;
    for (var i = 0; i < scripts.length; i++) {
        s[i] = document.createElement("script");
        s[i].setAttribute("type", "text/javascript");
        s[i].onload = s[i].onreadystatechange = function () { //Attach handlers for all browsers
            if (!0 || this.readyState == "loaded" || this.readyState == "complete") {
                loaded++;
                this.onload = this.onreadystatechange = null;
                this.parentNode.removeChild(this);
                if (loaded == scripts.length && typeof (callback) == "function") callback();
            }
        };
        s[i].setAttribute("src", scripts[i]);
        HEAD.appendChild(s[i]);
    }
}



// 日期 2015-09-01 11:16:00 data 是时间戳
function FormatDateTime(date, minType, point) {
    let _data = new Date(date);
    let y = _data.getFullYear();
    let m = _data.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    let d = _data.getDate();
    d = d < 10 ? ('0' + d) : d;
    let h = _data.getHours();
    h = h < 10 ? ('0' + h) : h;
    let minute = _data.getMinutes();
    minute = minute < 10 ? ('0' + minute) : minute;
    let seconds = _data.getSeconds();
    seconds = seconds < 10 ? ('0' + seconds) : seconds;
    let _sep = '-';
    if (point) _sep = point;

    // 最小到天
    if (minType == 'minDay') {
        return y + _sep + m + _sep + d
    }
    // 最小到分钟
    else if (minType == 'minMinute') {
        return y + _sep + m + _sep + d + ' ' + h + ':' + minute
    }
    // 最小到秒
    else {
        return y + _sep + m + _sep + d + ' ' + h + ':' + minute + ':' + seconds;
    }
}


//

/**
 * 判断是否是微信浏览器
 * @returns {Boolean}
 */
function isWeiXin() {
    let ua = window.navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) == 'micromessenger') {
        return true;
    } else {
        return false;
    }
}

/**
 * 判断是否是支付宝浏览器
 * @returns {boolean}
 */
function isAlipay() {
    let ua = window.navigator.userAgent.toLowerCase();
    if (ua.match(/AlipayClient/i) == 'alipayclient') {
        return true;
    } else {
        return false;
    }
}

/**
 * 判断是否是QQ内置浏览器
 * @returns {boolean}
 */
function isQQ() {
    let ua = window.navigator.userAgent.toLowerCase();
    if (ua.match(/QQ/i) == 'qq') {
        if (ua.match(/qqbrowser/i) == 'qqbrowser') {
            // console.log('QQ浏览器')
            return false;
        }
        else {
            return true;
        }
    } else {
        return false;
    }
}


// 获取样式
function getStyle (obj, attr) {
    if(obj.currentStyle) {
        return obj.currentStyle[attr];
    }
    else {
        return getComputedStyle(obj, false)[attr];
    }
}

// 获取class
function hasClass(obj, cls) {
    return obj.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}

// 添加class
function addClass(obj, cls) {
    if ( !hasClass(obj, cls) ) obj.className += " " + cls;
}

// 移除class
function removeClass(obj, cls) {
    if (hasClass(obj, cls)) {
        let reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
        obj.className = obj.className.replace(reg, ' ');
    }
}

// 动态添加class
function toggleClass(obj,cls){
    if(hasClass(obj,cls)){
        removeClass(obj, cls);
    }else{
        addClass(obj, cls);
    }
}

// 获取window的滚动高度
function getWinScrollTop() {
    let scrollTop = 0;
    if(document.documentElement && document.documentElement.scrollTop) {
        scrollTop = document.documentElement.scrollTop;
    }
    else if( document.body ) {
        scrollTop = document.body.scrollTop;
    }
    else if ( window.pageYOffset ) {
        scrollTop = window.pageYOffset;
    }
    return scrollTop;
}

// offset属性
function offset(target) {
    let top = 0,
        left = 0;
    while(target.offsetParent) {
        top += target.offsetTop;
        left += target.offsetLeft;
        target = target.offsetParent;
    }
    return {
        top: top,
        left: left,
    }
}

// 运动效果
function startMove (obj, json, fn) {
    clearInterval(obj.timer);
    obj.timer = setInterval(function (){
        let bStop = true;		//这一次运动就结束了——所有的值都到达了
        for(let attr in json) {
            //1.取当前的值
            let iCur = 0;

            if(attr == 'opacity') {
                iCur = parseInt( parseFloat( getStyle(obj, attr) )*100 );
            }
            else {
                iCur = parseInt( getStyle(obj, attr) );
            }

            //2.算速度
            let iSpeed = ( json[attr] - iCur )/8;
            iSpeed = iSpeed>0 ? Math.ceil(iSpeed) : Math.floor(iSpeed);

            //3.检测停止
            if( iCur != json[attr] ) {
                bStop = false;
            }

            if( attr == 'opacity' ) {
                obj.style.filter = 'alpha(opacity:'+(iCur+iSpeed)+')';
                obj.style.opacity = (iCur+iSpeed)/100;
            }
            else {
                obj.style[attr] = iCur + iSpeed + 'px';
            }
        }

        if(bStop) {
            clearInterval(obj.timer);
            if(fn)  fn();
        }
    }, 25)
}

export {
    setCookie,
    getCookie,
    delCookie,

    CutTime,

    seriesLoadScripts,
    parallelLoadScripts,
    FormatDateTime,

    isWeiXin,
    isAlipay,
    isQQ,

    getStyle,
    startMove,
    hasClass,
    addClass,
    removeClass,
    toggleClass,
    offset,
    getWinScrollTop,
}